//Darius Smith
//DA5 part 2
//This project code will control the output of a stepper motor
//using a potentiometer and an analog in port

#define F_CPU 8000000UL		//XTAL = 8MHZ

#include <avr/io.h>
#include <stdio.h>
#include <avr/interrupt.h>
#include <util/delay.h>


void printStringToScreen(char *sentence) //function to output to screen
	{
	while ((*sentence !='\0'))
		{
		while(!(UCSR0A&(1<<UDRE0)));
			UDR0 = *sentence;
		sentence++;
		}
	}

int main()
	{
	char out_sentence[999];
	double val_adc;
	int val_ocr;
	
	DDRC = 0x00;	//All C ports set for inputs
	DDRB = 0xFF;	//All D ports set for outputs
	TCCR1B = 0x0D;	//Fast PWM with prescaler 1024	
	ADCSRA = 0x82;	//1000 0010 sets....
	UCSR0B = 0x08;  // TXEN0, bit 3, decimal value 8, is set high to enable the ATMega328p to transmit information, serially.
	UCSR0C = 0x06;  // UCSZ01 and UCSZ00, decimal values 4 and 2, are set high so that
	UBRR0 = 0x0033;
	
	while(1)
		{
		ADCSRA |= (1<<ADSC);
		
		while((ADCSRA&(1<<ADIF))==0)
			{
			}

		if (ADC < 70)
			{
			val_ocr = 250;
			}
		else if (ADC > 540)
			{
			val_ocr = 2000;
			}
		else
			{
			val_adc = ((ADC - 70) * 3.83) + 200;
			val_ocr = val_adc;
			}
		
		OCR1A = val_ocr;
		
		snprintf(out_sentence,sizeof(out_sentence), " %3d\r\n\n", ADC);
		printStringToScreen(out_sentence);
		
		//Takes turns changing the value of portB
		//It changes ADC input every time
		
		PORTB = 0x33;					// 0111 0111 = 51
		
		while((TIFR1 & (1<<OCF1A)) == 0)
			{
			}
		
		TIFR1 |= (1 << OCF1A);
		PORTB = 0X66;					// 0110 0110 = 102
		
		while((TIFR1 & (1<<OCF1A)) == 0)
			{
			}
			
		TIFR1 |= (1 << OCF1A);
		PORTB = 0x99;					// 1001 1001 = 153
		
		while((TIFR1 & (1<<OCF1A)) == 0)
			{
			}
			
		TIFR1 |= (1 << OCF1A);
		PORTB = 0xCC;					// 1100 1100 = 204
		
		while((TIFR1 & (1<<OCF1A)) == 0)
			{
			}
			
		TIFR1 |= (1 << OCF1A);
		}
	return 0;
	}